/**
 * @author klv
 */
var QS_advancedSearchConfig={
	fixedCriteria:['OS01W'],
	templeteType:"52",//advancedSearch list
	inLineArray:['STA4B','STA4D'],
	fixView:['OS01W', 'OS001'],
	exportList:[
		{txt:"Excel",val:'xls'},
		{txt:"WatchList",val:'wl'},
		{txt:"XML",val:'xml'}
    ],
	tabMenuData:[
		{
			txt: 'All Search',
			id: 'ALL',
			closable: false
		},{
			txt: 'Stock',
			id: 'ST',
			closable: false
		}, {
			txt: 'Mutual Fund',
			id: 'FO',
			closable: false
		}, {
			txt: 'Closed End Fund',
			id: 'FC',
			closable: false
		}, {
			txt: 'ETF',
			id: 'FE',
			closable: false
		},{
			txt: 'Indexes',
			id: 'XI',
			closable: false
		}
	],
	defaultFilter:{
		"ALL":['LS01Z','OS01V','OS010','OS05J','OS05K'],//Exchange,Exchange Country,Security Type,ISIN,CUSIP
		"ST": ['OS01V','LS01Z', 'STA4M','STA4J',
				'HS05A', 'RR01Y', 'LT155',
				'ST203', 'ST159', 'LA03Z','ST816'],
		'FO':['OS01V', 'LF035','OS63L', 'LS012', 'HS00L', 'RR01Y', 'HS949','LF002'],
		'XI':['LS01Z', 'LI021', 'LS05M', 'LI022'],
		'FC':['OS01V', 'LS01Z', 'LF035', 'RR01Y', 'HS00L', 'HS949', 'OS00C', 'LF002'],
		'FE':['OS01V', 'LS01Z','LF035',
			  'RR01Y', 'HS00L','LF002',
			  'OS00C']
	},
	operateBarConfig:{"default":false,"pdf":false}
};


var QS_advancedSearch=function($contain,config,callback){
	this.curTabID="ALL";
    this.filters={};
    this.container=$contain;
    this.cacheDataofTab={};//cache each tabmenu's default filter
    this.lastHeightChange=0;
    this.firstTag=true;
    var self=this;
    this.callback={};
    $.extend(self.callback,callback);
    this.currentSearchItemID=-1;//saved search filter
    this.staticValue={
        viewTab:28,
        operateBar:25,
		searchBar:34,
		filterHeight:170,
        pageBar:30,
        vertical:2,
        winTitle:26,
        horizontal:2,
		minWidth:700,
		componentTag:"advancedSearch"
    };
    this.config = {
        canExport: true,
        pageSize: 40,
		clickTicker:false,//config whether trigger click event
        dragable:false,
        clickTicker:true,
        isDefault:false,
        needOperBar:true,
		selectable:true,
        exportWLMax: 500,
        IDRMax:100,
        exportExcelMax: 2000,
        exportXMLMax: 2000,
        gridMinWidth:635,
        fixHeight:true,
		activeTab:"ALL",
        isAPI:true,
        sortbyall:true//config whether sort by all 
    };
    this.cacheColsData={};//cache each tabmenu view colnums
	this.cacheCurFilter=[];//cache dynamic filter
    this.cacheDefaultFilter={};//cache default condition when fetch data from backend , only usaged in base search
    this.sortCache=String.format("{0}:1",this.tickerCode);
    this.isCheckAll=false;
    this.selectedData=[];
    this.unselectedData=[];
    this.win=null;
	this._init();
};

QS_advancedSearch.prototype=$.extend(true,{},QS_BaseSearch,QS_advancedSearchConfig,{
	_init:function(){
		this.baseSearchInit();
		if(this.config.activeTab){
			this.curTabID=this.config.activeTab;
		}
		var self=this;
        if (this.config.isAPI) {
              this.el=$(this._getHtml()).appendTo(this.container);
			  this.loadingEl = this.el.find(".qs-search-loading");
        }
        else{
            this.win = new Util.RtqWindow(document.body, {
                windowReady: function(obj){
                    obj.setHtml(self._getHtml());
                    self.el = obj.el.find(".qs-search");
					self.container=self.el.parent();
                },
                beforeClosed: function(){
					
                },
                onResized: function(win, width, height){
                    self.changeOutSize(width, height);                    
                }
            }, {
                title: "Advanced Search",
                top: 100,
                width: 950,
                height: 700,
                resizable: false,
                isGlobal: true,
                hasSettingPanel: false,
                closeAction: 'hide'
            });
            if (typeof rtqWindowGroup != 'undefined') {
                rtqWindowGroup.register(this.win);
            }
        }
		this._genTabMenu();
		this._genGrid();
		this._genPage();
		this._genFilter();
		if(this.config.selectable){
			this.searchChoice=new QS_searchChoice(this.el.find('.qs-search-choice'),{
				onSave:function(cols){
					var data=self._getFilterData();
					self.cacheColsData={};//clear columns
					self.dynamicFilter.removeAllRow();
					self.bindFilterData({items:cols,selected:data.selected},function(){
						if(self.currentSearchItemID !=-1){
							self.reSearch(0);
						}
					});
				}
			});
			this.searchAddButton=this.el.find(".qs-search-filter .ft .add");
		}
		if(this.config.canExport){
			this.exportMenu = new Util.CascadeMenu($('.qs-search'), {
                autoHide: true,
	            display: false
            },this.exportList, {
	                onClick: function(item){
						self._exportToFile(item.data);
	                }
	        });
		}
		this._setMoreButton();
		this.body=this.el.find('.qs-search-filter .bd');
		if (this.config.needOperBar) {
			this.saveSearch=new QS_SearchSave(this.templeteType,{
				onSaveBefore:function(){
					self.onShowLoading();
				},
				onSaveAfter:function(sucess,id){
					if(sucess){}
					self.onHideLoading();
				},
				onSaveasBefore:function(){
					self.onShowLoading();
				},
				onSaveasAfter:function(sucess,id,name){
					if(sucess){
						self.currentSearchItemID =id;
						self.operateBar.setButtonDisable("save", false);
                        self._setDefaultButton();
                        self.operateBar.setName(name);
					}
					self.onHideLoading();
				},
				onDeleteBefore:function(){
					self.onShowLoading();
				},
				onDeleteAfter:function(sucess,id){
					if(sucess){
						if(self.currentSearchItemID == id){
							self.curTabID="ALL";
							self.selectMySearch();
						}
					}
					self.onHideLoading();
				},
				onClose:function(){
					self.operateBar.clearOn();
				}
			});
			this._genOperatoeBar();
		}
		if (this.config.openID&&this.config.openID!="-1") {
            this.selectMySearch(this.config.openID);
        }else {
            this.selectMySearch(this.config.isDefault=='true'?Terminal.getConfig("defaultCriterion"):'-1');
        }
        this.hoverobj=new AdvancedSearch_HoverTip();
        this._bindEvent();
    },
	_exportToFile:function(data){
        var type=data.val;
        var total=this.page.config.total;
        var needExportCount;
        if(this.isCheckAll){
            needExportCount=total-this.unselectedData.length;
        }else{
            needExportCount=this.selectedData.length;
        }
        var isOverMax=false;
        var Max=0;
        switch (type) {
            case "idr":
                 Max=this.config.IDRMax;
                 break
            case 'xls':
                 Max=this.config.exportExcelMax;
                 break;
            case 'wl':
                 Max=this.config.exportWLMax;
                 break;
            case 'pdf':
            case 'xml':
                 Max=this.config.exportXMLMax;
                 break;
            default:
                 break;
        }
        isOverMax = needExportCount > Max;
        if (needExportCount == 0) {
            Util.message(QS_Lang.screener.norecords);
        }
        else {
            if (isOverMax) {
                Util.message(String.format(QS_Lang.screener.overmax, data.txt, Max));
            }
            else {
                var self = this;
                Util.confirm(String.format(QS_Lang.screener.exportconfirm,data.txt,needExportCount,needExportCount>1?"s":""), function(b){
                    if (b) {
                        var sort=self.sortCache.split(":");
						self.exportData(type,self.isCheckAll,self.getCode(sort[0]),sort[1],total);
                    }
                }, {
                    title: "Report Confirm"
                });
            }
        }
	},
	exportData:function(type,isAll,sortfield,sorttype,total){
		var globequery=this._getQueryCondition(),unselectedStr=null,viwCols=this.cacheColsData[this.curTabID];
		var data={
			file: type,
			gridcol: $.toJSON(viwCols),
			name:"SearchReport"
		}
		if(sortfield){
			if(sortfield==this.keyWordCode) sortfield=this.replaceKeyWordCode;
			data["sortfield"]=sortfield;
        }
        if(sorttype){
            data["sorttype"]=sorttype;
        }
		var specialCode=this.PIdCode;
		if (this.curTabID=='FE'&&type=='idr'){//if export idr and securitytype is fe
            specialCode=this.SIdCode;
        }
		if(isAll){
			if(globequery.query['Keywords'].length == 0){
	            Util.message(QS_searchConfig.ExportPrompt);
				return;
	        }
			var unselectedStr=[];
			for(var i=0,l=this.unselectedData.length;i<l;i++){
	            unselectedStr.push(this.unselectedData[i][this.PIdCode]);
	        }
			data.type='all';
			data.total=total;
			data.query = $.toJSON(globequery.query),
			data.unselected=$.toJSON(unselectedStr);
			data.file=type;
			data.cols=$.toJSON({
	                Columns: [].concat([this.PIdCode],viwCols)
	            });
		}else{
			data.type='sel';
			data.selected=$.toJSON(this.selectedData);
		}
        if (type=='idr'||type=='wl') {//only export sID/pID
            data.exportField=specialCode;
            if (typeof data.cols != 'undefined') {
				data.cols = $.toJSON({
	                Columns: [specialCode]
				});
            }
            this.exportToOtherComponent(data,type);
        }
        else {
            if(type == 'pdf'){
                data.securityType=this.curTabID=="ST"?"Stock":"Exchange Traded Fund";
            }
            DBHelper.openWindowWithPost(data);
        }
	},
	exportToOtherComponent:function(data,type){
        data.file="wl";
        DBHelper.post(DBHelper.URLs.searchExport,data, function(o){
            if (o == 'false') {
                Util.message(QS_searchConfig.ExportFailed);
            }
            else {
                switch (type) {
                    case "wl":
                        var tempurl = String.format("api.jsp?instid={0}&module=watchlist&data=streaming", instid);
                        api_common_openwindow.openWindow(String.format("{0}&symbols={1}", tempurl, o), "WatchList");
                        break;
                    case "idr":
                       SiteBuilder_firstLoadLoginPage();
                       var i=0,symbols=o.split(',').join('|');
                       var self=this;
                       if (STATIC_VAR.marketIndexSessionExists == false) {
                           this.interval = setInterval(function(){
                                if (i < 10) {
                                    i++;
                                    if(STATIC_VAR.marketIndexSessionExists ==true){
                                        api_common_openwindow.openWindow("https://awrd.morningstar.com/SB/Data/GetIDRDetailReport.aspx?disclosure=1&universe=10&datasrc=AWD&stkprem=1&instid=SBDEMO&lang=en-US&tool=Screener&symbol="+symbols,"IDR");
                                        clearInterval(self.interval);
                                    }
                                } else {
                                    clearInterval(self.interval);
                                }
                           }, 1000);
                        }else{
                             api_common_openwindow.openWindow("https://awrd.morningstar.com/SB/Data/GetIDRDetailReport.aspx?disclosure=1&universe=10&datasrc=AWD&stkprem=1&instid=SBDEMO&lang=en-US&tool=Screener&symbol="+symbols,"IDR");
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    },
	onShowLoading:function(){
        if (this.win) {
            this.win.contentMask.show();
        }else{
            this.loadingEl.show();
        }
    },
	clear:function(){
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    },
    onHideLoading:function(){
        if (this.win) {
            this.win.contentMask.hide();
        }else {
            this.loadingEl.hide();
        }
    },
	_genOperatoeBar:function(){
		var self=this;
		this.operateBar=new QS_SearchOperateBar(this.el.find(".qs-operator"),$.extend({
			separator:"|",
            name:false,
			clear:true,
			"new":false,
			idr:false,
			"openTxt":"My search",
			"openClass":"qs-search-extend",
			"deleteClass":"qs-search-extend",
			curNameOnOpen:true
			},this.operateBarConfig||{}),{
            "onOpen":function(event){
				var data={
					type:self.templeteType,
					trigger:event,
					title:"",
					container:$('.qs-search'),
					hightLight:[self.currentSearchItemID],
					onClick:function(e,data){
						self.cacheColsData={};//clear columns
						self.dynamicFilter.removeAllRow();
						self.selectMySearch(data.id);
					},
					afterShow:function(moredialog){
						self._bindUnMoreDialogEvent(moredialog);
					}
				};
				self.saveSearch.list(data);
            },"onSave":function(event){
				var saveddata = self.getSavedData();
				if (saveddata.cansave) {
					var sort=self.sortCache.split(":");
					saveddata.data.sorttype=sort[1];
					saveddata.data.sortfield=sort[0];
					self.saveSearch.save(self.currentSearchItemID,saveddata.data);
				}
			},"onSaveas":function(event){
				var saveddata = self.getSavedData();
				if (saveddata.cansave) {
					var sort=self.sortCache.split(":");
					saveddata.data.sorttype=sort[1];
					saveddata.data.sortfield=sort[0];
					self.saveSearch.saveAs(saveddata.data);
				}
			},"onDelete":function(event){
				var data={
					type:self.templeteType,
					trigger:event,
					title:"",
					container:$('.qs-search'),
					hightLight:[self.currentSearchItemID],
					onClick:function(e,data){
						self.saveSearch.remove(data.id,"Delete Advanced Search");
					},
					afterShow:function(moredialog){
						self._bindUnMoreDialogEvent(moredialog);
					}
				};
				self.saveSearch.list(data);
			},"onClear":function(event){
				self.dynamicFilter.clearAllRow();
			}
		});
	},
	_bindUnMoreDialogEvent:function(moredialog){
		var self=this;
		this.el.unbind("click.moredialog").bind("click.moredialog",function(e){
			e.stopPropagation();
			var obj = $(e.target);
			var className = obj.attr("class")||"";
			if(className.indexOf(" ")!=-1){
				className = className.substring(0,className.indexOf(" "));
			}
			if(className!="open"&&className !="delete"){
				if ($(e.target).closest(".rtq-scrollbar").length == 0||$(e.target).closest(".qs-c").length>0) {
					moredialog.hide();
					$('.qs-operator .qs-search-extend').removeClass('on');
					self.el.unbind("click.moredialog");
				}
			}
		});
	},
	_setDefaultButton:function(){
        if(this.currentSearchItemID==-1||Terminal.getConfig("defaultCriterion")==this.currentSearchItemID){
            this.operateBar.setButtonDisable("default",true);
        }
        else{
            this.operateBar.setButtonDisable("default",false);
        }
    },
	_getHtml: function(){
		var str='<div class="qs-search">'+
		'<div class="qs-search-loading"><img src="common/loading.gif" /></div>'+
		'<div class="qs-gd">'+
		'<div class="hd"><div class="qs-search-tab"></div></div>'+
		'<div class="bd content"><div class="qs-search-filter">'+
		'<div class="hd"><div class="qs-extend">extend</div><div class="qs-fixedcriteria"></div><div class="qs-operator"></div></div>'+
		'<div class="bd"></div>'+
		'<div class="ft">'+(this.config.canExport?'<a href="#" class="qs-ui-btn export">Export</a>':'')+
		(this.config.selectable?'<a href="#" class="qs-ui-btn add">Add more...</a>':'')+'<a href="#" class="qs-ui-btn search">Search</a></div></div>'+
		'<div class="qs-search-result"><div class="qs-no-info">No data available.</div></div></div>'+
		'<div class="ft"><div class="qs-research-pagination"></div></div></div><div class="qs-search-choice"></div></div>';
		return str;
	},
	_genTabMenu:function(){
		var self=this;
		this.tabmenu = new Util.TabMenu(this.el.find('.qs-search-tab'), this.tabMenuData, {
                onActive: function(tab){
					self.curTabID=tab.id;
					self._setMoreButton();
					self.cacheColsData={};//clear columns
					self.clearSelectedItemValue();//clear dynamic selected data
					self.dynamicFilter.removeAllRow();
					self.selectMySearch();
                }
            }, {
                width: 80,
                isExcuteCallbackAtInit: false,
                tabsList: false
            });
	},
	_setMoreButton:function(){
		if(this.config.selectable){
			if(this.curTabID=="ALL"){
				this.searchChoice.hide();
				this.searchAddButton.hide();
			}else{
				this.searchAddButton.show();
			}
		}
	},
	_getQuickTakeURL:function(ticker){
        var data={"module":"research","symbol":ticker},urlCfg=api_common_openwindow.getLocationArg();
        data.submodule="quicktake_"+(this.curTabID=='FE'?"etf":"st");
		for(var attr in urlCfg){
            if(attr=='theme'||attr=='instid'){
                data[attr]=urlCfg[attr];
            }
        }
        return api_common_openwindow.genURL(data);
        
    },
	_genGrid:function(){
		var self=this;
		this.dataGrid=new Util.DataGrid(this.el.find('.qs-search-result'),{},{
            column: [],
			fixSize: true,
			htmlLayer: 'div',
			delayResize:false,
			rowDragDropGroup: 'gridDDGroup',
			rowDragable:this.config.dragable,
			autoHeight: !this.config.fixHeight,
			indexColKey: this.indexColKey
        }, {
                onCellMouseover: function(e, cell, row){
                    var key=cell.key;
                    if($.inArray(key,self.inLineArray)!=-1){//two special need be displaied in line
                        self.hoverobj.show(e,cell.text);
                    }
                },
                onCellMouseout: function(e, cell, row){
                    self.hoverobj.hide();
                },
				onSortedbyCell:function(cellkey,lastorder,callback){
                    var sorttype=lastorder=="ASC"?"2":"1";
                    self.cacheData={}//clear data cache
                    self.unselectedData=[];//clear unselectedData cache
                    self.selectedData=[];//clear selectedData cache
                    if (self.sortCache != self.getCode(cellkey) + ":" + sorttype) {
                        self.reSearch(self.page.getCurrentInfo().start-1, self.getCode(cellkey), sorttype);
                    }
                },
				onCellClick:function(e,cell,row){
                    if(!self.config.clickTicker) return;
                    if (cell.el.find("input").length > 0) return;
					var URL=self._getQuickTakeURL(row.data[self.PIdCode]);
                    if (typeof self.callback.onTickerClick == 'function') {
                        self.callback.onTickerClick({
                            component: self.staticValue.componentTag,
                            ticker: row.data[self.PIdCode],
                            url: URL
                        });
                    }
                    else {
                        if (cell.dataType == 'link') {
							if(self.curTabID=='FE'||self.curTabID=='ST'){
								api_common_openwindow.openWindow(URL,"Quicktake");
							}
                        }
                    }
				}
			}
		);
	},
	_genPage:function(){
		var self=this;
		this.page=new Util.PageUtil($('.qs-research-pagination'),{
                onClick:function(startAt,endAt){
                    self.searchOperate(startAt-1);
                }
            },{
                navSize:10,
                pageSize:this.config.pageSize,
                curPage:0,
                total:0
            }
		);
	},
	_genFilter:function(){
		if(!this.dynamicFilter){
			var self=this;
			this.dynamicFilter = new QS_DynamicAddRow(this.el.find('.qs-search-filter .bd'),[],{filterHeight:this.staticValue.filterHeight},
			{
				onClearRow:function(event,key){
					self.filters[key]["selected"] = [];
				},
				onRemoveRow:function(event,key){
					delete self.filters[key];
				}
			});
		}
	},
	selectMySearch:function(id){
		var self=this;
		this.reBindDataGrid([], []);
        if (typeof id != 'undefined'&&id!=null && id != "-1") {
            if(id==this.currentSearchItemID) return;
            self.saveSearch.getSearchData(id, function(data){
                if (data == null) {
                    self.selectMySearch();   
                }
                else {
					if(self.curTabID!=data.tabID){
						self.clearSelectedItem();
						self.curTabID=data.tabID;
						self.tabmenu.changeTabById(data.tabID,false);
					}
                    if (data.sortfield) {
                        self.sortCache = data.sortfield + ":" + data.sorttype;
                    }
                    self.bindFilterData(data,function(){self.reSearch();});
                    self.currentSearchItemID = id;
					if (self.config.needOperBar) {
						self.operateBar.setButtonDisable("save", false);
						self.operateBar.setName(data.title||self.saveSearch.getSearchNameByID(id));
					}
                }
            });
        }else{
            this.currentSearchItemID = -1;
			this.tabmenu.changeTabById(this.curTabID,false);
            this.bindFilterData();
			if (this.config.needOperBar) {
				this.operateBar.setButtonDisable("save", true);
				this.operateBar.setName();
			}
        }
	},
	_getDefaultFilterField:function(curTabID){
        if (!this.cacheDataofTab[curTabID]) {//cache default tabmenu filter
			this.cacheDataofTab[curTabID]=[].concat(this.fixView,this.defaultFilter[curTabID],[this.securityTypeCode],this.fixedCriteria||[],Search_DefaultData.search_DataKey);
        }
        return  this.cacheDataofTab[curTabID];
	},
	_getFilterField:function(filters){//dynamic get filters
		if(filters.length>0){
			return [].concat([this.securityTypeCode],this.fixView,filters,Search_DefaultData.search_DataKey);
		}else{
			return this._getDefaultFilterField(this.curTabID);
		}
	},
	_isSelected:function(indexColKeyValue){
        if (this.isCheckAll) {
            var data = this.unselectedData;
            for (var l = data.length, i = 0; i < l; i++) {
                if (data[i][this.indexColKey] == indexColKeyValue) {
                    return false;
                }
            }
            return true;
        }
        else {
            var data = this.selectedData;
            for (var l = data.length, i = 0; i < l; i++) {
                if (data[i][this.indexColKey] == indexColKeyValue) {
                    return true;
                }
            }
            return false;
        }
    },
	_convertToInstidCode:function(sData){
		var savedData={},items=[];
		if(typeof sData!='undefined'){
			if(sData.selected){
				for(var code in sData.selected){
					savedData[this.getCode(code)]=sData.selected[code];
				}
			}
			if(sData.items){
				for(var i=0,l=sData.items.length;i<l;i++){
					items.push(this.getCode(sData.items[i]));
				}
			}
		}
		return {items:items,selected:savedData}
	},
	bindFilterData:function(sData,callback){
		this.onShowLoading();
		var tData=this._convertToInstidCode(sData);//similar with the quest
		var items=tData.items,self=this,savedData=tData.selected;
        this.cacheCurFilter=items;
        this.getDynamicData(this._getFilterField(items),function(datamap){//sucess callback
			var code=null,fixedCriteria=self.fixedCriteria,tempData=null;
			for(var i=0,l=fixedCriteria.length;i<l;i++){//fix filter
				code=fixedCriteria[i],tempData=savedData[code];
				if (self.firstTag) {
					self.filters[code] = {status: "fix",selected: []};
					$.extend(true, self.filters[code], self.selectedItem[code]);
				}
				if (tempData) {
					self.filters[code].selected = tempData;
				}
			}
            self._genFixedFilter();
			if(items.length==0){
				self.cacheCurFilter=items=self.defaultFilter[self.curTabID];//get default filter
			}
			for(var i=0,l=items.length;i<l;i++){
				code=items[i];
				self.filters[code]={status:"dynamic",selected: []};
				$.extend(true,self.filters[code],self.selectedItem[code]);
				if(savedData[code]){
					self.filters[code].selected = savedData[code];
				}
			}
			self._cacheViewColumns([].concat(self.fixView,self.cacheCurFilter));//cache colnumns
			self.dynamicFilter.addRows(self.filters);
			if (self.firstTag) {
				Util.DelayRun(self.staticValue.componentTag+'.onload', self.loadHandler, 100, self);
				self.firstTag=false;
			}
			self.onHideLoading();
			if(typeof callback!='undefined'){
				callback();
			}
        },function(){//failed callback
			Util.message(QS_Lang.screener.searchfailed);
            self.onHideLoading();
		});
	},
	reSearch:function(start, sortfiled, sorttype){
        this.isCheckAll=false;
        this.selectedData=[];
        this.unselectedData=[];
		this.searchOperate(start, sortfiled, sorttype);
	},
	searchOperate:function(start,sortfield,sorttype){
        this.onShowLoading();
        var page=Math.floor(start/this.config.pageSize)+1;
        var sort=this.sortCache.split(":");
		var self=this;
		this.getSearchResult(function(data,total,error){
			if(typeof error!='undefined'&&error) {self.onHideLoading();return;}
			self._searchCallback(self.curTabID,page,start,total,data);
			//cache sort statu
			if (sortfield && sorttype) {
				self.sortCache = sortfield + ":" + sorttype;
			}
			self.dataGrid.setSortICON(self.getCode(sortfield||sort[0]),(sorttype||sort[1])=="1"?"ASC":"DESC");

		},start,this.config.pageSize,[].concat(this.cacheCurFilter,this.fixView,Search_DefaultData.search_DataKey),this.getCode(sortfield||sort[0]),sorttype||sort[1]);      
	},
	_cacheViewColumns:function(cols){
		if(!this.cacheColsData[this.curTabID]){
            this.cacheColsData[this.curTabID]=this.getViewCols(cols);
        }
	},
	_searchCallback:function(currenttab,page,start,total,data){
        this.reBindDataGrid(this._setOperateCol(this.cacheColsData[currenttab]),data);
        var pageConfig={curPage:page}
        if(total){
            pageConfig.total=total;
        }
        this.page.rebind(pageConfig);
        if (this.firstTag) {
            Util.DelayRun(this.staticValue.componentTag+'.onload', this.loadHandler, 100, this);
        }
        else {
            Util.DelayRun(this.staticValue.componentTag+'.heightchange', this.heightChangeHandler, 100, this);
        }
        this.onHideLoading();
    },
	loadHandler:function(){
        if(typeof this.callback.onLoad=='function'){
            this.callback.onLoad({
                component: this.staticValue.componentTag,
                height: this.el.height(),
                minWidth : this.staticValue.minWidth
            });
        }
    },
	heightChangeHandler:function(){
		 if(!this.config.fixHeight&&typeof this.callback.onHeightChange=='function'){
			var height=this.el.height(),width=this.el.width();
			if(this.lastHeight!=height){
				this.callback.onHeightChange({
					component: this.staticValue.componentTag,
					height: height,
					width : width
				});
				this.lastHeight=height;
			}
		}
	},
	_setOperateCol:function(cols){
        var colsadd=[];
        $.extend(true,colsadd,cols);
        var self=this,length=colsadd.length;
        //add the gridconfig
        if(this.config.sortbyall){
            for(var i=0;i<length;i++){
                colsadd[i].refetch=true;
            }
        }
        if(colsadd.length>0&&this.config.canExport){
            colsadd.unshift({
                header: '<a herf="javascript:void(0);" class="qs-search-selectall">'+(this.isCheckAll?"Unselect":"Select")+'</a>',
                dataIndex: self.indexColKey,
                width: 60,
                align: 'center',
                sortable: false,
                renderer: function(txt){
                    return self._isSelected(txt)?'<input key="' + txt + '" type="checkbox" checked>':'<input key="' + txt + '" type="checkbox">';
                }
            });
        }
        return colsadd;
    },
	reBindDataGrid:function(cols,data){
        this.dataGrid.setColumnCfg(cols);
        this.dataGrid.reBindData(data);
		if(cols.length!=0&&data.length==0){
			this.el.find(".qs-no-info").show();
		}else{
			this.el.find(".qs-no-info").hide();
		}
        this._reBindGridEvent();
        this.changeOutSize();
    },
	changeOutSize:function(outwidth,outheight){
		var container=this.container.parent();
		var w=outwidth||container.innerWidth(),h=outheight||container.innerHeight();
		if(this.win){h=h-this.staticValue.winTitle;}
        var minWidth= this.staticValue.minWidth;
		if(this.config.isAPI){
			if (isNaN(this.config.width)) {
				w=Math.max(minWidth,w);
			}else{
				w=Math.max(this.config.width,minWidth);
			}
		}
        var resultH = h - this.staticValue.vertical-this.staticValue.viewTab- this.staticValue.pageBar - this.staticValue.operateBar-this.staticValue.searchBar-(this.dynamicHide?0:this.staticValue.filterHeight);
        var resultW =w-this.staticValue.horizontal;
		
        if (this.config.fixHeight) {
			this.el.css({width: w+"px",height:h+"px"});
            this.dataGrid.resize(resultW, resultH);
        }
        else {
			this.el.css({width: w+"px"});
            this.dataGrid.resize(resultW, 'auto');
        }
		this.dynamicFilter.setFilterScroll();
    },
	_reBindGridEvent:function(){
        var selectAllCell = this.dataGrid.header.row.cells[this.indexColKey];
        var self=this;
        if(selectAllCell){
            selectAllCell.el.unbind("click").click(function(e){
                e.stopPropagation();
                self.isCheckAll=!self.isCheckAll;
                self.unselectedData=[];
                self.selectedData=[];
                if(self.isCheckAll){
                    $(this).find(".qs-search-selectall").text("Unselect");
                }else{
                    $(this).find(".qs-search-selectall").text("Select");
                }
                for (var r in self.dataGrid.rows) {
                    self.dataGrid.rows[r].cells[self.indexColKey].el.find('input')[0].checked = self.isCheckAll;
                }
            });
            self.dataGrid.el.find('input').click(function(e){
                if(!$(this).hasClass("qs-grid-selectall")){
                    var txt=$(this).attr('key');
                    if (self.isCheckAll) {
                        if (!this.checked) {
                            var data = self.unselectedData;
                            for (var l = data.length, i = 0; i < l; i++) {
                                if (data[i][self.indexColKey] == txt) {
                                    return;
                                }
                            }
                            self.unselectedData.push(self.dataGrid.rows[txt].data);
                        }else{
                            for(var i=0,l=self.unselectedData.length;i<l;i++){
                                if(self.unselectedData[i][self.indexColKey]==txt){
                                    self.unselectedData.splice(i,1);
                                    break;
                                }
                            }
                        }
                    }else{
                        if(this.checked){
                            var data = self.selectedData;
                            for (var l = data.length, i = 0; i < l; i++) {
                                if (data[i][self.indexColKey] == txt) {
                                    return;
                                }
                            }
                            self.selectedData.push(self.dataGrid.rows[txt].data);
                        }else{
                            for(var i=0,l=self.selectedData.length;i<l;i++){
                                if(self.selectedData[i][self.indexColKey]==txt){
                                    self.selectedData.splice(i,1);
                                    break;
                                }
                                
                            }
                        }
                    }
                    if(typeof (self.callback.onClickCheckbox)=='function'){
                        self.callback.onClickCheckbox({
                            component:self.staticValue.componentTag,
                            ticker:self.dataGrid.rows[txt].data[self.getCode(self.tickerCode)],
                            pid:self.dataGrid.rows[txt].data[self.indexColKey],
                            check:this.checked
                        });
                        //self.dataGrid.rows[txt],this.checked);
                    }
                }
            }
            );
        }
    },
	_genFixedFilter:function(){
        var code=null,fixedCriteria=this.fixedCriteria,dom=this.el.find('.qs-fixedcriteria');
        for(var i=0,l=fixedCriteria.length;i<l;i++){
            code=fixedCriteria[i];
			if (this.firstTag) {
				this.dynamicFilter.addRow(dom,this.filters[code]);
			}else{
				this.dynamicFilter.domMap[code].dom.filter.setDefault(this.filters[code].selected);
			}
        }
    },
	_changeCollapseHeight:function(bool){
        if(bool){
            var h=document.documentElement.clientHeight-118;
            var w=document.documentElement.clientWidth;
            this.dataGrid.resize(w, h);
        }else{
            this.changeOutSize();
        }
    },
	_bindEvent:function(){
        var self=this;
		//collapse menu
		var self=this;
		this.el.find('.qs-extend').bind("click",function(e){
            var container=self.el.find('.qs-search-filter');
            if($(this).hasClass('qs-collapse')){
                $(this).removeClass('qs-collapse');
                container.css({height:self.staticValue.operateBar+self.staticValue.searchBar+self.staticValue.filterHeight+"px"});
                self.body.show();
                self.dynamicHide=false;
                self._changeCollapseHeight(false)
            }else{
                $(this).addClass('qs-collapse');
                self.body.hide();
                self.dynamicHide=true;
                container.css({height:self.staticValue.operateBar+self.staticValue.searchBar+"px"});
                self._changeCollapseHeight(true)
            }
        });
        this.el.find(".qs-search-filter .ft").bind("click",function(e){
			if (e.target.tagName.toUpperCase() == "A") {
                var obj = $(e.target);
                if (obj.hasClass("export")) {
					var topoffset=self.staticValue.viewTab+self.staticValue.operateBar+(self.dynamicHide?0:self.staticValue.filterHeight);
					var xy = obj.position();
					self.exportMenu.setPosition(xy.left+10, xy.top+20+topoffset);
					self.exportMenu.show();
                }else if(obj.hasClass("add")){
					self.searchChoice.edit({// search Choice only support local code
						secType: self.curTabID,
						cols:self.getDynamicCode()
					});
				}else if(obj.hasClass("search")){
					self.reSearch(0);
				}
            }
		});
    }
});


var AdvancedSearch_HoverTip = function(){
    var timeout = null;
    var tipEl = $("<div class='qs-search-tip'></div>").appendTo($('.qs-search-result'));
    tipEl.css({position:'absolute'});
    var appendData=function(data){
        var array=data.split(',');
        var flag=false;
        for(var i=0,l=array.length;i<l;i++){
            if ($.trim(array[i]) != '') {
                flag=true;
                tipEl.append(String.format('<span style="diplan">{0}</span>',array[i]));
            }
        }
        return flag;
    }
    return {show:function(e,data){
                if (appendData(data)) {
                    tipEl.show();
                    tipEl.css({
                        left: e.clientX + 10,
                        top: e.clientY + 10
                    });
                }
            },
            hide:function(){
                tipEl.empty();
                tipEl.hide();
            }
        }
};
